package org.zhadoop.streaming.util.datatype;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import javax.xml.crypto.Data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zhadoop.streaming.config.StreamingConfig;
import org.zhadoop.streaming.exception.StreamingException;

import com.google.common.base.Strings;

/**
 * 日期类型解析
 * @author zwd
 *
 */
public class DateParser implements DataTypeParser {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8938525160479818781L;

	private static final Logger LOG = LoggerFactory.getLogger(DateParser.class);
	
	private final SimpleDateFormat dateFormatter;
	
	private final TimeZone timeZone;
	
	public DateParser(StreamingConfig config) throws StreamingException{
		timeZone = TimeZoneUtils.parseTimeZone(TimeConstants.ZERO_TIMEZONE);
		dateFormatter = new SimpleDateFormat(TimeConstants.DATE_FORMAT);
		dateFormatter.setLenient(false);
		dateFormatter.setTimeZone(timeZone);
	}
	
	@Override
	public Object createValue(String value) throws StreamingException {
		if(Strings.isNullOrEmpty(value)){
			return null;
		}
		if(value.length() > TimeConstants.DATE_FORMAT.length()){
			LOG.warn("Failed to create {} instance." , Data.class.getName());
			throw new StreamingException("Failed to create " + Date.class.getName() + " instance. ");
		}
		
		try {
			java.util.Date  uDate = dateFormatter.parse(value);
			return new java.sql.Date(uDate.getTime());
		} catch (Exception e) {
			LOG.warn("Failed to create {} instance .",Date.class.getName() );
			throw new StreamingException("Failed to create " + Date.class.getName() + " instance.");
		}
	}

	@Override
	public String toStringValue(Object value) throws StreamingException {
		if(null == value){
			return null;
		}
		return dateFormatter.format(value);
	}

}
